package com.imediawork.mysimpleaudioplayer;

import android.media.MediaPlayer;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends Activity implements View.OnClickListener {

	private MediaPlayer mediaPlayer;
	private EditText audioPath;
	private Button loadButton, playPauseButton, stopButton;
	
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        audioPath = (EditText)findViewById(R.id.audioPath);
        loadButton = (Button)findViewById(R.id.loadButton);       
        playPauseButton = (Button)findViewById(R.id.playPauseButton);
        stopButton = (Button)findViewById(R.id.stopButton);
        loadButton.setOnClickListener(this);
        playPauseButton.setOnClickListener(this);
        stopButton.setOnClickListener(this);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
    
	@Override
	protected void onDestroy() {
		if (mediaPlayer != null) {
			mediaPlayer.release();
			mediaPlayer = null;
		}
		super.onDestroy();
	}

	@Override
	public void onClick(View v) {
		if (v == loadButton) {
			if (loadAudio(audioPath.getText().toString()) == true) {
		    	playPauseButton.setEnabled(true);
		    	stopButton.setEnabled(true);
		    	loadButton.setEnabled(false);
			}
		} else if (v == playPauseButton) {
			if (mediaPlayer.isPlaying()) {
				mediaPlayer.pause();
				playPauseButton.setText("Play");
			} else {
				mediaPlayer.start();
				playPauseButton.setText("Pause");
			}
		} else if (v == stopButton) {
			mediaPlayer.stop();
			mediaPlayer.release();
			playPauseButton.setText("Play");
			playPauseButton.setEnabled(false);
	    	stopButton.setEnabled(false);
	    	loadButton.setEnabled(true);
		}
	}
    
    private boolean loadAudio(String path)
    {
    	try {
            mediaPlayer = new MediaPlayer();
			mediaPlayer.setDataSource(path);
	    	mediaPlayer.prepare();
	    	return true;
		} catch (Exception e) {
			Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
			return false;
		}
    }
}
